package com.myeasyexcel.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.lang.reflect.Field;

/**
 * @author wangXiaoHu
 * @date 2022/03/24 09:28
 **/
@Slf4j
public class DropDownSheetWriteHandler implements SheetWriteHandler {
    private static Integer LAST_ROW = 1000000;
    /**
     * Called before create the sheet
     *
     * @param writeWorkbookHolder
     * @param writeSheetHolder
     */
    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }
    public static void setDropDownBox(Sheet sheet,DataValidationHelper helper, String[] values, Integer firstRow, Integer lastRow, Integer col) {
        // 设置下拉单元格的首行 末行 首列 末列   【因为我的业务是第一行是描述 ，第二行是列头，第三行是内容  所以入参下标从2开始，暂定5000行，可以写最大行，也可以根据业务而定】
        CellRangeAddressList rangeList = new CellRangeAddressList(firstRow, lastRow, col, col);
        // 下拉列表约束数据
        DataValidationConstraint constraint = helper.createExplicitListConstraint(values);
        // 设置约束
        DataValidation validation = helper.createValidation(constraint, rangeList);
        // 阻止输入非下拉选项的值
        validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
        validation.setShowErrorBox(true);
        validation.setSuppressDropDownArrow(true);
        validation.createErrorBox("提示", "此值与单元格定义格式不一致");
        sheet.addValidationData(validation);
    }

    /**
     * Called after the sheet is created
     *
     * @param writeWorkbookHolder
     * @param writeSheetHolder
     */
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();

        Class clazz = writeSheetHolder.getClazz();
        // 通过注解获取字段上面的内容 和 顺序
        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields){
            DropDownOptions downOptions = field.getAnnotation(DropDownOptions.class);
            if(downOptions == null){
                continue;
            }
            String[] options = downOptions.options();
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            int col = excelProperty.index();
            setDropDownBox(sheet,helper,options,1,LAST_ROW,col);
            //firstRow,标题行
        }
    }
}

